#include <SDL.h>
#include <iostream>
#include <fstream>
#include <vector>
#ifdef main
#undef main
#endif
// 音频参数
const int SAMPLE_RATE = 44100;
const int CHANNELS = 2;
const int SAMPLE_FORMAT = 16; // 16位采样

// 音频数据结构
struct AudioData {
    Uint8* pos;
    Uint32 length;
};

// 音频回调函数
void audioCallback(void* userdata, Uint8* stream, int len) {
    AudioData* audio = (AudioData*)userdata;
    
    if (audio->length == 0) {
        return;
    }
    
    Uint32 length = (len > audio->length ? audio->length : len);
    SDL_memcpy(stream, audio->pos, length);
    
    audio->pos += length;
    audio->length -= length;
}

int main(int argc, char* argv[]) {
    if (argc < 2) {
        std::cerr << "Usage: " << argv[0] << " <pcm_file>" << std::endl;
        return -1;
    }
    
    // 读取PCM文件
    std::ifstream file(argv[1], std::ios::binary);
    if (!file.is_open()) {
        std::cerr << "Failed to open PCM file: " << argv[1] << std::endl;
        return -1;
    }
    
    // 将文件内容读入缓冲区
    file.seekg(0, std::ios::end);
    size_t file_size = file.tellg();
    file.seekg(0, std::ios::beg);
    
    std::vector<Uint8> buffer(file_size);
    file.read((char*)buffer.data(), file_size);
    file.close();
    
    // 初始化SDL
    if (SDL_Init(SDL_INIT_AUDIO) < 0) {
        std::cerr << "Failed to initialize SDL: " << SDL_GetError() << std::endl;
        return -1;
    }
    
    // 设置音频格式
    SDL_AudioSpec want, have;
    SDL_zero(want);
    want.freq = SAMPLE_RATE;
    want.format = AUDIO_S16LSB; // 16位小端序有符号整数
    want.channels = CHANNELS;
    want.samples = 4096; // 音频缓冲区大小
    want.callback = audioCallback;
    
    AudioData audio;
    audio.pos = buffer.data();
    audio.length = file_size;
    want.userdata = &audio;
    
    // 打开音频设备
    SDL_AudioDeviceID device = SDL_OpenAudioDevice(NULL, 0, &want, &have, 0);
    if (device == 0) {
        std::cerr << "Failed to open audio device: " << SDL_GetError() << std::endl;
        SDL_Quit();
        return -1;
    }
    
    // 开始播放音频
    SDL_PauseAudioDevice(device, 0);
    
    // 等待播放完成
    while (audio.length > 0) {
        SDL_Delay(100);
    }
    
    // 清理资源
    SDL_CloseAudioDevice(device);
    SDL_Quit();
    
    std::cout << "Playback finished." << std::endl;
    return 0;
}